import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:getx_study/mode/MovieItem.dart';
import 'package:getx_study/video_list/view.dart';

import 'package:video_player/video_player.dart';

class VideoPlayerPage extends StatefulWidget {

  const VideoPlayerPage({
    Key? key,
    this.title = 'Chewie Demo',
  }) : super(key: key);

  final String title;

  @override
  State<StatefulWidget> createState() {
    return _VideoPlayerPageState();
  }
}

class _VideoPlayerPageState extends State<VideoPlayerPage> {
  late VideoPlayerController _videoPlayerController1;
  ChewieController? _chewieController;
  MovieItem movieItem = Get.arguments;

  @override
  void initState() {
    super.initState();
    initializePlayer();
  }

  @override
  void dispose() {
    super.dispose();
  }
  //https://v2.88zy.site/20210407/3Vepx5Wq/index.m3u8
  //https://assets.mixkit.co/videos/preview/mixkit-daytime-city-traffic-aerial-view-56-large.mp4
  //https://v2.88zy.site/20210507/tAzTg47f/index.m3u8
  Future<void> initializePlayer() async {
    _videoPlayerController1 = VideoPlayerController.network(movieItem.url);
    await Future.wait([
      _videoPlayerController1.initialize(),
    ]);
    _createChewieController();
    setState(() {});
  }

  void _createChewieController() {
    _chewieController = ChewieController(
      videoPlayerController: _videoPlayerController1,
      autoPlay: true,
      looping: true,
      subtitleBuilder: (context, dynamic subtitle) => Container(
        padding: const EdgeInsets.all(10.0),
        child: subtitle is InlineSpan
            ? RichText(
          text: subtitle,
        )
            : Text(
          subtitle.toString(),
          style: const TextStyle(color: Colors.black),
        ),
      ),
      // Try playing around with some of these other options:
      showControls: true,
      materialProgressColors: ChewieProgressColors(
        playedColor: Colors.red,
        handleColor: Colors.blue,
        backgroundColor: Colors.grey,
        bufferedColor: Colors.lightGreen,
      ),
      placeholder: Container(
        color: Colors.grey,
      ),
      autoInitialize: true,
    );
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        width: size.width,
        height: 235,
        child: getChewieView()
      ),
    );
  }

  Widget getChewieView() {
    return _chewieController != null && _chewieController!.videoPlayerController.value.isInitialized ?
      Chewie(controller: _chewieController!) :
      Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: const [
          CircularProgressIndicator(),
          SizedBox(height: 20),
          Text('Loading')]
    );
  }
}
